package ntu.metaweb.http;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.util.HashMap;

import ntu.metaweb.Metaweb;
import ntu.metaweb.storage.BinaryRating;
import ntu.metaweb.storage.WebPageKey;
import ntu.metaweb.update.UpdateCommentRating;
import ntu.p2p.dht.DHTContent;
import ntu.p2p.dht.messaging.DHTObjectDifference;
import ntu.p2p.dht.messaging.DHTUpdateObjectMessage;
import rice.Continuation;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;

@SuppressWarnings("restriction")
public class UpdateCommentRatingHandler implements ntu.metaweb.http.CommandHandler {

	@Override
	public void handleCommand(final HttpExchange exchange,
			final HashMap<String, String> params) throws IOException {
		final WebPageKey key = new WebPageKey(
				URLDecoder.decode(params.get("url"), "UTF-8"));
		final boolean up = Boolean.parseBoolean(params.get("up"));
		
		Metaweb.getInstance().getDhtApplication().lookup(key, 
				new Continuation<DHTContent,Exception>() {

					@Override
					public void receiveException(Exception exception) {
						System.out.println("exception");
					}

					@Override
					public void receiveResult(DHTContent result) {
						// create and insert web page query object
						System.out.println("update comment rating");
						int id = Integer.parseInt(params.get("comment_id").substring(8));
						DHTObjectDifference diff = new UpdateCommentRating(id,
								new BinaryRating(params.get("username"), up ? 1 : -1));
						DHTUpdateObjectMessage updateMessage = 
							new DHTUpdateObjectMessage(key,	diff);
						Metaweb.getInstance().getDhtApplication().update(key, updateMessage, 
								new Continuation<Object, Exception>() {

									@Override
									public void receiveException(Exception exception) {
										// TODO Auto-generated method stub
										
									}

									@Override
									public void receiveResult(Object result) {
										System.out.println("update successs");
										onReceiveResult(exchange, result);
									}
						});
						
					}
		});
	}

	protected void onReceiveResult(HttpExchange exchange, Object result) {
		try {
			System.out.println("sending update success...");
			Headers responseHeaders = exchange.getResponseHeaders();
			responseHeaders.set("Content-Type", "text/xml");

			exchange.sendResponseHeaders(200, 0);

			OutputStream responseBody = exchange.getResponseBody();
			String temp = "<xmlresponse>\n" 
					+ "<returncode>1</returncode>\n"
					+ "</xmlresponse>";
			responseBody.write(temp.getBytes());
			responseBody.close();
			exchange.close();
			System.out.println("close update comment rating handler");

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			exchange.close();
			System.out.println("close update comment rating handler");
		}
	}

}
